package org.dfg.corejava.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class SocketRequest {
	public static void main(String[] args) {
		SocketChannel sc = null;
		InetSocketAddress address = new InetSocketAddress("www.baidu.com", 80);
		try {
			sc = SocketChannel.open();
			sc.configureBlocking(true);
			sc.connect(address);

			Charset c = Charset.forName("GBK");
			while(!sc.finishConnect()){}
			sc.write(c.encode("GET / HTTP/1.1\r\n\r\n"));
			ByteBuffer bb = ByteBuffer.allocate(1024);
			while (sc.read(bb) != -1) {
				bb.flip();
				CharBuffer s = c.decode(bb);
				bb.clear();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				sc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
